package com.example.smart.order.controller;

import com.example.smart.order.entity.Category;
import com.example.smart.order.entity.Dish;
import com.example.smart.order.mapper.CategoryMapper;
import com.example.smart.order.mapper.DishMapper;
import com.example.smart.order.mapper.OrderInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

/**
 * 菜品控制器，处理与菜品相关的HTTP请求
 */
@RestController
@Slf4j
@RequestMapping("/api/dishes")
public class DishController {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private Environment env;

    /**
     * 增加菜品
     *
     * @param dish 菜品对象
     * @return 处理结果，1表示成功，-1表示失败
     */
    @PostMapping("/addNew")
    public int addNew(@RequestBody Dish dish) {
        log.debug("增加菜品: {}", dish);
        Category category = categoryMapper.selectById(dish.getCategoryId());
        if (category == null) {
            log.debug("菜品类别不存在，categoryId: {}", dish.getCategoryId());
            return -1;
        }
        dish.setImage("/image/dish_default.png"); // 菜品的默认图片
        int result = dishMapper.insert(dish);
        log.debug("增加菜品结果: {}", result);
        return result;
    }

    /**
     * 根据ID删除菜品
     *
     * @param dishId 菜品ID
     * @return 处理结果，1表示成功，-1表示失败
     */
    @PostMapping("/delete")
    public int delete(Long dishId) {
        log.debug("删除菜品, ID: {}", dishId);
        int count = orderInfoMapper.countByDishIdAndNotPaid(dishId);
        if (count > 0) {
            log.debug("存在未结账订单，删除操作被阻止");
            return -1;
        }
        int result = dishMapper.deleteById(dishId);
        log.debug("删除菜品结果: {}", result);
        return result;
    }

    /**
     * 根据ID修改菜品
     *
     * @param dish 菜品对象
     * @return 处理结果，1表示成功，-1表示失败
     */
    @PostMapping("/update")
    public int update(@RequestBody Dish dish) {
        log.debug("修改菜品: {}", dish);
        int count = orderInfoMapper.countByDishIdAndNotPaid(dish.getId());
        if (count > 0) {
            log.debug("存在未结账订单，修改操作被阻止");
            return -1;
        }
        Category category = categoryMapper.selectById(dish.getCategoryId());
        if (category == null) {
            log.debug("菜品类别不存在，categoryId: {}", dish.getCategoryId());
            return -1;
        }
        int result = dishMapper.updateById(dish);
        log.debug("修改菜品结果: {}", result);
        return result;
    }

    /**
     * 根据ID查询菜品
     *
     * @param dishId 菜品ID
     * @return 菜品对象
     */
    @RequestMapping("/query")
    public Dish query(Long dishId) {
        log.debug("查询菜品, ID: {}", dishId);
        Dish dish = dishMapper.selectById(dishId);
        log.debug("查询到菜品: {}", dish);
        return dish;
    }

    /**
     * 根据类别ID获取菜品列表
     *
     * @param categoryId 菜品类别ID
     * @return 菜品列表
     */
    @RequestMapping("")
    public List<Dish> getDishesByCategory(Long categoryId) {
        log.debug("获取菜品列表，categoryId: {}", categoryId);
        List<Dish> dishes = dishMapper.selectByCategoryId(categoryId);
        log.debug("查询到菜品列表: {}", dishes);
        return dishes;
    }

    /**
     * 处理上传菜单图片请求
     *
     * @param dishId 菜品ID
     * @param file   上传的图片文件
     * @return 处理结果，1表示成功，-1表示失败
     */
    @PostMapping("/updateImage")
    public int updateImage(@RequestParam Long dishId, @RequestParam MultipartFile file) {
        log.debug("处理上传菜单图片请求，dishId: {}", dishId);

        // 读取自定义属性“保存上传文件的文件夹”的值
        String uploadDir = env.getProperty("file.upload-dir");
        if (uploadDir == null || uploadDir.isEmpty()) {
            log.error("上传文件夹路径未配置");
            return -1;
        }

        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            log.debug("上传文件为空");
            return -1;
        }

        // 检查文件类型是否为JPEG或PNG
        String contentType = file.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) {
            log.debug("上传文件类型不支持");
            return -1;
        }

        // 检查文件大小是否小于10MB
        long fileSize = file.getSize();
        if (fileSize > 10 * 1024 * 1024) {
            log.debug("上传文件大小超过限制");
            return -1;
        }

        // 查询菜品数据
        Dish dish = dishMapper.selectById(dishId);
        if (dish == null) {
            log.debug("菜品不存在，dishId: {}", dishId);
            return -1;
        }

        // 保存文件到指定目录
        String fileName = UUID.randomUUID().toString() + "." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String dishImageDir = uploadDir + "/dish_image";
        Path uploadPath = Paths.get(dishImageDir);
        if (!Files.exists(uploadPath)) {
            try {
                Files.createDirectories(uploadPath);
            } catch (IOException e) {
                log.error("创建目录失败: {}", dishImageDir, e);
                return -1;
            }
        }
        Path filePath = uploadPath.resolve(fileName);
        try {
            file.transferTo(filePath.toFile());
        } catch (IOException e) {
            log.error("保存文件失败: {}", filePath, e);
            return -1;
        }

        // 更新菜品图片路径
        dish.setImage("/dish_image/" + fileName);
        int result = dishMapper.updateById(dish);
        log.debug("更新菜品图片路径结果: {}", result);

        return result;
    }
}